/**
* @file  EventsItem
* @author xiao_xie
* @date 2025-03-24
*/


import { QuestionCircleOutlined, DownOutlined, SearchOutlined, DeleteOutlined, SettingOutlined, AimOutlined } from '@ant-design/icons';
import { Space, Button, Popover, Modal, Card, message } from 'antd';
import React, { useEffect, useState } from 'react';
import ClickIcon from '../../../../assets/click.svg';
import YesIcon from '../../../../assets/yes.svg'
import { useCurrentComponent } from '../../../../hooks/useCurrentComponent';
import EInput from '../../../EInput/EInput';
import { debounce } from '../../../../utils/utils';
import { useVisble } from '../../../../hooks/useVisble';
import SelectItem from './SelectItem';

const EventsItem: React.FC = () => {
    const { events, pageJs, addPageJs, currentId, setBindEvents, currentElement } = useCurrentComponent();
    const inputRef = React.useRef<any>(null);
    const modalProps = useVisble({ title: '事件绑定' });
    const [defaultMethod, setDefaultMethod] = useState<string>('ClickNewMethod');
    const [currentMethodName, setCurrentMethodName] = useState(defaultMethod);
    const searchOnChange = debounce((e: string) => {
        console.log(111, e)
    })

    const handleOnclickMethod: React.MouseEventHandler<HTMLDivElement> = (e) => {
        const target = e.target as HTMLElement;
        if (target.className.includes('item')) {
            // ...原有样式逻辑
            const items = document.querySelectorAll('.item');
            items.forEach(item => {
                item.classList.remove('active');
            });
            target.classList.add('active');
            // 如果是"添加新方法"选项
            if (target.innerText === '添加新方法') {
                setCurrentMethodName(''); // 清空输入框
            } else {
                setCurrentMethodName(target.innerText); // 同步方法名到输入框

            }
        }
    }

    // 修改handleOk方法
    const handleOk = () => {
        if (!inputRef.current?.validate()) return; // 验证不通过
        if (!addPageJs) return
        let obj = {
            isSelected: true, // 不选中
            desc: modalProps.rowValue, // 是什么事件类型
            name: currentMethodName,  // 使用状态值
            type: 'function',
            code: `function ${currentMethodName}() { }`
        }
        addPageJs(obj)
        if (setBindEvents && currentId)
            setBindEvents(currentId, obj)
        modalProps.onOk();
    }

    // 修改handleCancel方法
    const handleCancel = () => {
        setCurrentMethodName(defaultMethod); // 重置为默认值
        modalProps.onCancel();
    }


    return <div>
        <Space>
            <Button icon={
                <Popover
                    placement="bottom"
                    content={<div>支持添加原生 DOM 事件，添加后点击 <strong className='text-orange-400'>绑定事件</strong> 为画布中所选元素增加事件</div>}
                >
                    <QuestionCircleOutlined />
                </Popover>
            } size='small' iconPosition={"end"} color="default" variant="filled">
                添加自定义事件
            </Button>
            <Popover placement="bottom" content={<div className='bg-white rounded-sm flex flex-col gap-1'>
                {
                    events.map((item) => {
                        // 判断是否允许选中，根据 desc 字段
                        const isAllowed = !currentElement?.bindEvents?.some(
                            bindEvent => bindEvent.desc === item.desc && bindEvent.isSelected
                        );
                        return <div
                            className={`cursor-pointer p-2 ${isAllowed ? 'hover:bg-[#F2F2F2]' : 'opacity-50 cursor-not-allowed'}`}
                            key={item.type}
                            onClick={() => {
                                if (isAllowed) {
                                    modalProps.showModal(item.desc);
                                }
                            }}
                        >
                            {item.desc}
                        </div>
                    })
                }
            </div>} >
                <Button icon={<DownOutlined />} size='small' iconPosition={"end"} color="default" variant="filled">
                    绑定事件
                </Button>
            </Popover>
        </Space>
        <div className='mt-4'>
            {
                currentElement?.bindEvents && currentElement.bindEvents.length > 0 ? currentElement?.bindEvents?.map((item) => {
                    return (
                        <SelectItem desc={item.desc} name={item.name} key={item.name} />
                    );
                }) : <div className='flex flex-col items-center gap-3 mt-3' >
                    <img src={ClickIcon} />
                    元素事件绑定
                    <p>点击 <strong className='text-orange-400'>绑定事件</strong> 为画布中所选元素增加事件</p>
                </div>
            }
        </div>


        <Modal   {...modalProps} onOk={handleOk} onCancel={handleCancel}>
            <div className='flex gap-4'>
                <Card title="响应方法" style={{ width: 280 }}>
                    <EInput onChange={searchOnChange} allowClear icon={<SearchOutlined />} iconPosition='end' />
                    <div className='mt-3 flex flex-col gap-3' onClick={handleOnclickMethod}>
                        <div className='p-1 bg-[#fff] flex justify-between item new-item cursor-pointer active'>添加新方法 <img src={YesIcon} className='opacity-0' /></div>
                        {
                            pageJs?.map((item) => {
                                return <div className='p-1 bg-[#fff] flex justify-between item cursor-pointer' key={item.name}>{item.name} <img src={YesIcon} className='opacity-0' /></div>
                            })
                        }
                    </div>
                </Card>
                <Card title="方法名称" variant="borderless" className='flex-1'>
                    <EInput
                        ref={inputRef}
                        required
                        // disabled={currentMethodName !== 'ClickNewMethod'}  // 当选择添加新方法时，输入框只读
                        value={currentMethodName}  // 改为受控value
                        onChange={(value) => setCurrentMethodName(value)}  // 添加onChange
                        placeholder='请从左侧选择一个方法进行绑定，或者选择添加新方法，输入自定义方法名称。'
                    />
                    <p className='text-xs mt-2'>*选择已有方法或者添加新方法(点击 确定 之后将在JS面板中创建一个该名称的新方法)</p>
                </Card>
            </div>
        </Modal>
    </div>
}
export default EventsItem;
